package com.lclz.service.security;

import java.util.ArrayList;
import java.util.List;

import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.cas.userdetails.AbstractCasAssertionUserDetailsService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

@SuppressWarnings("deprecation")
public class UserDetailsService extends AbstractCasAssertionUserDetailsService {

	final protected Logger logger = LoggerFactory.getLogger(UserDetailsService.class);
	private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD";

	@SuppressWarnings("unused")
	private final String[] attributes;

	@SuppressWarnings("unused")
	private boolean convertToUpperCase = true;

	public UserDetailsService(final String[] attributes) {
		// logger.info("loggin:" + attributes);
		Assert.notNull(attributes, "attributes cannot be null.");
		Assert.isTrue(attributes.length > 0, "At least one attribute is required to retrieve roles from.");
		this.attributes = attributes;
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	protected UserDetails loadUserDetails(final Assertion assertion) {
		// logger.info("loggin:" + assertion);
		final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		String roles = (String) AuthenticationUtil.getConfigValue(assertion.getPrincipal().getName());
		if (!CheckUtil.isEmpty(roles)) {
			String[] roleArray = roles.split(",");
			if (!CheckUtil.isEmpty(roleArray)) {
				for (String role : roleArray) {
					grantedAuthorities.add(new GrantedAuthorityImpl(role));
				}
			} else {
				grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
			}
		} else {
			grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
		}
		UserDetail user = new UserDetail(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities);
		if (!CheckUtil.isEmpty(assertion.getPrincipal().getAttributes())) {
			user.setMap(assertion.getPrincipal().getAttributes());
		}
		return user;
	}

	/**
	 * Converts the returned attribute values to uppercase values.
	 * 
	 * @param convertToUpperCase
	 *            true if it should convert, false otherwise.
	 */
	public void setConvertToUpperCase(final boolean convertToUpperCase) {
		this.convertToUpperCase = convertToUpperCase;
	}
}
